# encoding: utf-8
import os
from datetime import datetime

from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.api import images
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

import models
import memcache_def

class BaseRequestHandler(webapp.RequestHandler):
	"""Base classs"""
	count_per_footer = memcache_def.get_count_per_footer_memcache()
	def generate(self, template_name, template_values={}):
		site_name = memcache_def.get_site_name_memcache()
		values = {
			'site_name': site_name
		}

		query_article_contents = models.Content.all().filter('type','article').order("-__key__")
		article_contents = query_article_contents.fetch(int(self.count_per_footer))
		if article_contents:
			values_contents = {
				'article_contents': article_contents
			}
			values.update(values_contents)
		values.update(template_values)
		directory = os.path.dirname(__file__)
		path = os.path.join(directory, os.path.join('templates', template_name))
		self.response.out.write(template.render(path, values))

class index_root(BaseRequestHandler):
	def get(self):
		values = {
		}
		self.generate(template_name='root_base.html',template_values=values)

class title_setting_root(BaseRequestHandler):
	def get(self):
		values = {
			'path': self.request.path
		}
		self.generate(template_name='title_setting_root_base.html',template_values=values)
	def post(self):
		title_site_value = self.request.get("title_site_text")
		title_site = models.Setting.all().filter('name','site_name').get()
		title_site.value = title_site_value
		title_site.put()
		memcache_def.update_site_name_memcache()
		self.redirect(self.request.uri)

class edit_default_root(BaseRequestHandler):
	def get(self):
		default_content = models.Content.all().filter('type','default').get()
		if default_content:
			default_content_value = default_content.content
		else:
			default_content_value = '暂时没有文章'
		values = {
			'path': self.request.path,
			'default_content': default_content_value
		}
		self.generate(template_name='edit_default_root_base.html',template_values=values)
	def post(self):
		update_default_content = self.request.get('default_content_textarea')
		default_content = models.Content.all().filter('type','default').get()
		if not default_content:
			default_content = models.Content(type='default')
		default_content.content = update_default_content
		default_content.put()
		self.redirect(self.request.uri)

class new_edit_article_root(BaseRequestHandler):
	def get(self):
		values = {
			'path': self.request.path
		}
		str_id = self.request.get('id')
		if str_id:
			edit_article = models.Content.get_by_id(int(str_id))
			value_update = {
				'edit_article': edit_article
			}
			values.update(value_update)
		self.generate(template_name='new_edit_article_root_base.html',template_values=values)
	def post(self):
		title_article = self.request.get('title_text')
		content_article = self.request.get('article_content_textarea')
		str_key = self.request.get('key_hidden')
		if str_key:
			article = db.get(db.Key(str_key))
			article.title = title_article
			article.content = content_article
			article.put()
			self.redirect(self.request.uri)
		else:
			article = models.Content(type='article')
			article.title = title_article
			article.content = content_article
			article.put()
			self.redirect(self.request.uri+'?id='+str(article.key().id()))

class delete_manage_article_root(BaseRequestHandler):
	def get(self):
		page_key = self.request.get('b')
		if page_key:
			page_key = models.Content.get_by_id(int(page_key)).key()
			articles = models.Content.all().filter('type =','article').order("-__key__").filter("__key__ <=",page_key).fetch(int(self.count_per_footer)+1)
			pre_article = models.Content.all().filter('type =','article').order("__key__").filter("__key__ >",page_key).fetch(int(self.count_per_footer))
		else:
			articles = models.Content.all().filter('type =','article').order("-__key__").fetch(int(self.count_per_footer)+1)
			pre_article = None
		if articles:
			for article in articles:
				article.time_date_2 = datetime.strftime(article.time_date,'%H:%M:%S %m月%d日 %Y年')
		values = {
			'path': self.request.path,
			'article_contents_self': articles[:int(self.count_per_footer)]
		}
		if len(articles) == int(self.count_per_footer)+1:
			values_page = {
				'next': articles[int(self.count_per_footer)]
			}
			values.update(values_page)
		if (pre_article) and (len(pre_article)>0):
			values_page_2 = {
				'pre': pre_article[-1]
			}
			values.update(values_page_2)
		self.generate(template_name='delete_manage_article_root_base.html',template_values=values)
	def post(self):
		del_key = self.request.get('delete_key_article')
		if del_key:
			db.delete(db.Key(del_key))
		self.redirect(self.request.uri)

class upload_file_root(BaseRequestHandler):
	def get(self):
		values = {
		}
		self.generate(template_name='upload_file.html',template_values=values)
	def post(self):
		img = self.request.get('img')
		image = models.Image()
		image.content = db.Blob(img)
		image.put()
		values = {
			'image': image
		}
		self.generate(template_name='upload_file.html',template_values=values)

class delete_image_root(BaseRequestHandler):
	def get(self):
		get_id = self.request.get("b")
		if get_id:
			get_key = models.Image.get_by_id(int(get_id)).key()
			images = models.Image.all().order("-__key__").filter("__key__ <=",get_key).fetch(int(self.count_per_footer)+1)
			pre_images = models.Image.all().order("__key__").filter("__key__ >",get_key).fetch(int(self.count_per_footer)+1)
		else:
			images = models.Image.all().order("-__key__").fetch(int(self.count_per_footer)+1)
			pre_images = None
		values = {
			'path': self.request.path,
			'images': images[:int(self.count_per_footer)]
		}
		if len(images) == int(self.count_per_footer)+1:
			values_add = {
				'next': images[int(self.count_per_footer)]
			}
			values.update(values_add)
		if (pre_images) and (len(pre_images)>0):
			values_add_2 = {
				'pre': pre_images[-1]
			}
			values.update(values_add_2)
		self.generate(template_name='delete_image_root_base.html',template_values=values)
	def post(self):
		str_key = self.request.get('delete_key_image')
		if str_key:
			db.delete(db.Key(str_key))
		self.redirect(self.request.uri)

class footer_setting_root(BaseRequestHandler):
	def get(self):
		values = {
			'path': self.request.path,
			'count_per_footer': self.count_per_footer
		}
		self.generate(template_name='footer_setting_root_base.html',template_values=values)
	def post(self):
		new_count_footer = self.request.get('count_footer_text')
		new_count_per_footer = models.Setting.all().filter('name =','count_per_footer').get()
		new_count_per_footer.value = new_count_footer
		new_count_per_footer.put()
		memcache_def.update_count_per_footer_memcache()
		self.redirect(self.request.uri)

class error_base(BaseRequestHandler):
	def get(self):
		values = {
		}
		self.generate(template_name='error_root.html',template_values=values)

def main():
	application = webapp.WSGIApplication([
		('/root.html$', index_root),
		('/title_setting_root.html$', title_setting_root),
		('/footer_setting_root.html$', footer_setting_root),
		('/edit_default_root.html$', edit_default_root),
		('/new_edit_article_root.html$', new_edit_article_root),
		('/delete_manage_article_root.html$', delete_manage_article_root),
		('/upload_file_root.html$', upload_file_root),
		('/delete_image_root.html$', delete_image_root),
		('/(.*)', error_base)
	], debug=True)
	run_wsgi_app(application)

if __name__ == '__main__':
	main()
